package com.ex01.ylw;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 读取本地文件并向客户端输出
 * Created by yangliwei on 2017/7/19.
 */
public class Response {
    private static final Integer BUFFER_SIZE = 1024;

    private Request request;
    private OutputStream out;

    public Response(OutputStream out) {
        this.out = out;
    }

    public void sendStaticResource() throws IOException {
        byte[] bytes = new byte[BUFFER_SIZE];
        FileInputStream fis = null;
        try {
            File file = new File(HttpServer.WEB_ROOT + request.getUri());
            if (file.exists()) {
                fis = new FileInputStream(file);
                int ch = fis.read(bytes, 0, BUFFER_SIZE);
                while (ch != -1) {
                    out.write(bytes,0,ch);
                    ch = fis.read(bytes, 0, BUFFER_SIZE);
                }
            } else {
                // file not found
                String errorMessage = "HTTP/1.1 404 File Not Found\r\n" +
                        "Content-Type: text/html\r\n" +
                        "Content-Length: 23\r\n" +
                        "\r\n" +
                        "<h1>File Not Found</h1>";
                out.write(errorMessage.getBytes());
            }
        }catch (Exception e){
            System.out.println(e.toString() );
        }finally {
            if(fis != null){
                fis.close();
            }
        }
    }

    public void setRequest(Request request) {
        this.request = request;
    }

    public void setOut(OutputStream out) {
        this.out = out;
    }
}
